import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Platform} from 'ionic-angular'
import {HTTP} from '@ionic-native/http';
import {Observable} from "rxjs/Observable";
import "rxjs/add/observable/of";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {BAIDULBSGEOTABLE} from "../../../config/url.config";

@Injectable()
export class ClientMapProvider {
    ak: string = 'CD677af3b1af2e72700794ef17d4ed04';
    geotableName: string = 'client_store_list';
    apiUrlPre: string = 'http://api.map.baidu.com';
    apiVersion: string = 'v3';
    geotable_id: string = BAIDULBSGEOTABLE;
    isMobileWeb: boolean;    //chrome模拟，需配置本地跨域
    page_index: number = 0;      //检索分页索引，默认0
    page_size: number = 50;      //检索条数，最大50(百度api限制)
    postHeadrs: HttpHeaders = new HttpHeaders().set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    agentCode = localStorage.getItem('userName');             //当前营销员code
    agentCodeInt:any = null;         //营销员code字母转成ASCII，组合格式为字母ASCII+原有数字
    baiduApi: any = {
        cloudgcApi: null,                   //地址转经纬度
        cloudrgcApi: null,                   //经纬度转地址
        createGeotableApi: null,            //创建位置数据表
        listGeotableApi: null,              //查询数据表
        detailGeotableApi: null,            //查询数据表详情
        geosearchRadiusApi: null,            //半径范围检索
        createPoiApi: null,                  //新增客户数据
        updatePoiApi: null,                  //更新客户数据
        deletePoiApi: null,                  //删除客户数据
        getUidByAgentClientCodeApi:null         //获取指定的百度lbs客户id
    };

    constructor(
        private angularHttp: HttpClient,
        public platform: Platform,
        private cordovaHttp:HTTP
    ) {
        this.isMobileWeb = this.platform.is('mobileweb');
        this.baiduApi.cloudgcApi = '/cloudgc/v1?geotable_id={0}&address={1}&ak={2}&output=json';
        this.baiduApi.cloudrgcApi = '/cloudrgc/v1?geotable_id={0}&location={1}&ak={2}&output=json';
        this.baiduApi.createGeotableApi = '/geodata/' + this.apiVersion + '/geotable/create?ak={0}';
        this.baiduApi.listGeotableApi = '/geodata/' + this.apiVersion + '/geotable/list?name={0}&ak={1}';
        this.baiduApi.detailGeotableApi = '/geodata/' + this.apiVersion + '/geotable/detail?id={0}&ak={1}';
        this.baiduApi.geosearchRadiusApi = '/geosearch/' + this.apiVersion + '/nearby?ak={0}&geotable_id={1}&location={2}&radius={3}&page_index={4}&page_size={5}&filter={6}';
        this.baiduApi.createPoiApi = '/geodata/' + this.apiVersion + '/poi/create';
        this.baiduApi.updatePoiApi = '/geodata/' + this.apiVersion + '/poi/update';
        this.baiduApi.deletePoiApi = '/geodata/' + this.apiVersion + '/poi/delete';
        this.baiduApi.getUidByAgentClientCodeApi = '/geodata/' + this.apiVersion + '/poi/list?ak={0}&geotable_id={1}&agent_client_code={2}$';
        this.getAgentCodeInt();
    }

    /**
     * 字母转ASCII码
     */
    getAgentCodeInt(){
        let codePre = this.agentCode.match(/[a-zA-Z]/g);
        let codePreInt = '';
        if(codePre&&codePre.length){
            codePre.map(e=>{
                codePreInt += e.charCodeAt(0);
            });
        }
        this.agentCodeInt = `${codePreInt}${this.agentCode.slice(codePre.length)}`;
    }

    /**
     * 拼接url参数
     * @param basePath
     * @param params
     * @returns {any}
     */
    getPath(basePath, params) {
        for (let i = 0; i < params.length; i++) {
            basePath = basePath.replace('{' + i.toString() + '}', params[i]);
        }
        return basePath;
    }

    /**
     * 参数序列化
     * @param obj
     * @returns {string}
     */
    formatUrlParams(obj: any) {
        let string = '';
        for (let k in obj) {
            string += '&' + k + '=' + obj[k];
        }
        string = string.substr(1);
        return string;
    }

    /**
     * @function 地址转经纬度
     * @param {string} address
     */
    cloudgc(address: string):Observable<any> {
        let url = this.getPath(this.apiUrlPre + this.baiduApi.cloudgcApi, [this.geotable_id, address, this.ak]);
        if(this.isMobileWeb){
            return this.angularHttp.get(url).map(r => {
                return r;
            });
        }else {
            url = encodeURI(url);
            // const promise = this.cordovaHttp.get(url,{},{}).then(r=>r.data);
            return Observable.create(observer=>{
                this.cordovaHttp.get(url, {}, {}).then(r => observer.next(r.data));
            });
        }
    }

    /**
     * @function 经纬度转地址
     * @param location
     * @returns {Observable<any>}
     */
    cloudrgc(location: any):Observable<any> {
        let url = this.getPath(this.apiUrlPre + this.baiduApi.cloudrgcApi, [this.geotable_id, `${location.lat},${location.lng}`, this.ak]);
        if(this.isMobileWeb){
            return this.angularHttp.get(url).map(r => {
                return r;
            });
        }else {
            url = encodeURI(url);
            // const promise = this.cordovaHttp.get(url,{},{}).then(r=>r.data);
            return Observable.create(observer=>{
                this.cordovaHttp.get(url, {}, {}).then(r => observer.next(r.data));
            });
        }
    }

    /**
     * @function 创建位置数据表
     * @param {string} name
     */
    createGeotable(name: string) {
        const url = this.getPath(this.apiUrlPre + this.baiduApi.createGeotableApi, [this.ak]);
        this.angularHttp.post(url, {
            name: name,
            geotype: 1,
            is_published: 1
        }).subscribe(r => {
            console.log(r);
            return r;
        })
    }

    /**
     * 查询数据表
     * @param {string} name
     */
    getListGeotable(name: string = this.geotableName) {
        const url = this.getPath(this.apiUrlPre + this.baiduApi.listGeotableApi, [name, this.ak]);
        this.angularHttp.get(url).subscribe(r => {
            console.log(r);
            return r;
        });
    }

    /**
     * 查询数据表详情
     * @param {string} id
     */
    getDetailGeotable(id: string = this.geotable_id) {
        const url = this.getPath(this.apiUrlPre + this.baiduApi.detailGeotableApi, [id, this.ak]);
        this.angularHttp.get(url).subscribe(r => {
            console.log(r);
            return r;
        });
    }


    /**
     * @function 半径检索
     * @param {string} location
     * @param {number} radius
     * @param {number} page_index
     * @param {number} page_size
     */
    geosearchRadius(location: string, radius: number, page_index: number = this.page_index, page_size: number = this.page_size): Observable<any> {

        const url = this.getPath(this.apiUrlPre + this.baiduApi.geosearchRadiusApi,
            [this.ak, this.geotable_id, location, radius, page_index, page_size,`agent_code_int:${this.agentCodeInt}`]);
        if(this.isMobileWeb){
            return this.angularHttp.get(url).map(r => {
                return r;
            });
        }else {
            // const promise = this.cordovaHttp.get(url, {}, {}).then(r => r.data);
            return Observable.create(observer=>{
                this.cordovaHttp.get(url, {}, {}).then(r => observer.next(r.data));
            })
        }
    }

    /**
     * 新增数据
     * @param {string} address  客户地址
     * @param {any} latlng 经纬度
     * @param {number} client_type 客户类型，1-准客户，2-核心客户,默认2，通过查询出来的数据都是核心客户
     * @param {string} client_id    客户ID
     * @param {string} agent_client_code    营销员-客户ID，联合id唯一索引
     *
     */
    createPoi(address: string, latlng: any, client_id: string,client_type:number):Observable<any> {
        const url = this.apiUrlPre + this.baiduApi.createPoiApi;
        let params = {
            ak: this.ak,
            address: address,
            longitude: latlng.lng,
            latitude: latlng.lat,
            client_type: client_type,
            agent_client_code: `${this.agentCode}${client_id}`,
            client_id:client_id,
            coord_type: 3,
            geotable_id: this.geotable_id,
            agent_code:this.agentCode,
            agent_code_int:this.agentCodeInt
        };

        if(this.isMobileWeb){
            return this.angularHttp.post(url, this.formatUrlParams(params), {headers: this.postHeadrs}).map(r => {
                return r;
            });
        }else{
            // const promise = this.cordovaHttp.post(url, params,'').then(r => r.data);
            return Observable.create(observer=>{
                this.cordovaHttp.post(url, params,'').then(r => observer.next(r.data));
            });
        }
    }

    /**
     * 更新客户数据
     * @param {number} id 百度云服务存的id
     * @param {string} address
     * @param {any} latlng    经纬度
     * @param {number} client_type  客户类型暂时不更新
     * @param {string} agent_client_code  根据联合id更新
     */
    updatePoi(address: string, latlng: any,agent_client_code?:string,id?: number,client_type?:number):Observable<any> {
        const url = this.apiUrlPre + this.baiduApi.updatePoiApi;
        let params:any = {
            ak: this.ak,
            address: address,
            longitude: latlng.lng,
            latitude: latlng.lat,
            coord_type: 3,
            client_type:client_type,
            geotable_id: this.geotable_id,
            agent_code:this.agentCode,
            agent_code_int:this.agentCodeInt
        };
        if(id){
            params.id = id;
        }
        if(agent_client_code){
            params.agent_client_code = agent_client_code;
        }
        if(this.isMobileWeb){
            return this.angularHttp.post(url, this.formatUrlParams(params), {headers: this.postHeadrs}).map(r => {
                return r;
            });
        }else {
            // const promise = this.cordovaHttp.post(url, params, {}).then(r => r.data);
            return Observable.create(observer=>{
                this.cordovaHttp.post(url, params, {}).then(r => observer.next(r.data));
            });
        }
    }

    /**
     * 删除客户，批量客户的id用，号隔开
     * @param ids
     */
    deletePoi(ids):Observable<any> {
        const url = this.apiUrlPre + this.baiduApi.deletePoiApi;
        let params: any = {
            ak: this.ak,
            geotable_id: this.geotable_id
        };
        if (ids.split(',').length > 1) {
            params.is_total_del = 1;
            params.ids = ids;
        } else {
            params.id = ids;
        }
        if(this.isMobileWeb){
            return this.angularHttp.post(url, this.formatUrlParams(params), {headers: this.postHeadrs}).map(r => {
                return r;
            });
        }else {
            // const promise = this.cordovaHttp.post(url, params, {}).then(r => r.data);
            return Observable.create(observer=>{
                this.cordovaHttp.post(url, params, {}).then(r => observer.next(r.data));
            });
        }
    }

    /**
     * 获取指定id的百度lbs数据
     * @param {string} agentClientCode
     * @returns {any}
     */
    getUidByAgentClientCode(agentClientCode:string):Observable<any>{
        const url = this.getPath(this.apiUrlPre + this.baiduApi.getUidByAgentClientCodeApi,
            [this.ak, this.geotable_id, agentClientCode]);
        if(this.isMobileWeb){
            return this.angularHttp.get(url).map(r => {
                return r;
            });
        }else {
            // const promise = this.cordovaHttp.get(url, {}, {}).then(r => r.data);
            return Observable.create(observer=>{
                this.cordovaHttp.get(url, {}, {}).then(r => observer.next(r.data));
            });
        }
    }

    /**
     * 从百度LBS删除准客户(弃用)
     * @param {string} clientNum
     */
    deleteClientLeadsForLBS(clientNum:string):Observable<any>{
        let agentClientCode = `${this.agentCode}${clientNum}`;
        let self = this;
        return Observable.create(observer=>{
            // this.getUidByAgentClientCode(agentClientCode).subscribe(x=>{
            //     if(!self.isMobileWeb) {
            //         x = JSON.parse(x);
            //     }
            //     if(x&&x.status == 0){
            //         if(x.size == 1){
            //             //存在数据，删除
            //             let uid = x.pois[0].id +'';
            //             self.deletePoi(uid).subscribe(r=>{
            //                 if(!self.isMobileWeb){
            //                     r = JSON.parse(r);
            //                 }
            //                 if(r&&r.status == 0){
            //                     observer.next(true);
            //                 }else {
            //                     observer.next(false);
            //                 }
            //             });
            //         }else {
            //             //不存在数据，跳过直接删除
            //             observer.next(true);
            //         }
            //     }else {
            //         //获取百度lbs错误，删除失败
            //         observer.next(false);
            //     }
            // });
            observer.next(true);
        });
    }

    /**
     * @function 更新LBS地址(弃用)
     * @param {string} address
     * @param {string} clientId
     * @param {number} client_type
     * @returns {Observable<any>}
     */
    updatePoiByClientId(address:string,clientId:string,client_type:number):Observable<any>{
        let agentClientCode = `${this.agentCode}${clientId}`;
        let self = this;
        return Observable.create(observer=>{
            // this.getUidByAgentClientCode(agentClientCode).subscribe(x=>{
            //     if(!self.isMobileWeb) {
            //         x = JSON.parse(x);
            //     }
            //     if(x&&x.status == 0){
            //         if(x.size == 1){
            //             //存在数据，触发更新
            //             self.cloudgc(address).subscribe(r=>{
            //                 if(!self.isMobileWeb) {
            //                     r = JSON.parse(r);
            //                 }
            //                 if(r&&r.status == 0){
            //                     if(r.result&&r.result.length){
            //                         let location = r.result[0].location;
            //                         self.updatePoi(address,location,agentClientCode,null,client_type).subscribe(data=>{
            //                             // alert(JSON.stringify(data));
            //                             observer.next(data);
            //                         });
            //                     }else {
            //                         observer.complete(r);
            //                     }
            //                 }else {
            //                     observer.complete(r);
            //                 }
            //             });
            //         }else {
            //             //不存在数据，触发新增
            //             self.cloudgc(address).subscribe(r=>{
            //                 if(!self.isMobileWeb) {
            //                     r = JSON.parse(r);
            //                 }
            //                 if(r&&r.status == 0){
            //                     if(r.result&&r.result.length){
            //                         let location = r.result[0].location;
            //                         self.createPoi(address,location,clientId,client_type).subscribe(data=>{
            //                             observer.next(data);
            //                         });
            //                     }else {
            //                         observer.complete(r);
            //                     }
            //                 }else {
            //                     observer.complete(r);
            //                 }
            //             });
            //         }
            //     }else {
            //         observer.complete(x);
            //     }
            // });
            observer.next(true);
        });
    }
}
